﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;

namespace Client
{
    public class SocketConnection
    {
        #region Headers
        public const int RECV_SESSION_KEY = 0x01,
            PAK_LOGIN_REQUEST = 0x02;
        #endregion

        public static Socket ClientSocket;
        public static void Connect()
        {
            try
            {
                ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                ClientSocket.Connect(IPAddress.Parse("127.0.0.1"), 7000);
                while (true)
                {
                    if (ClientSocket.Connected)
                        ReceiveData();
                    else
                    {
                        // Do Something
                    }
                }
            }
            catch
            {

            }
        }

        public static void ReceiveData()
        {
            DataPacket dp = new DataPacket();
            byte[] buf = new byte[1452];
            dp.dwRecvSize = ClientSocket.Receive(buf);
            dp.buffer = buf;
            ParseData(dp);
        }

        public static void ParseData(DataPacket dp)
        {
            if (dp.dwRecvSize < 5)
            {
                ClientSocket.Disconnect(false);
                ClientSocket.Close();
            }
            dp.dwPointer = 5;
            int header = dp.Readint32();

            switch (header)
            {
                case RECV_SESSION_KEY:
                    MessageBox.Show("Session Key Received!");
                    break;
            }
        }
    }
}
